package com.ympc.controller;

import com.ympc.pojo.Assignment;
import com.ympc.pojo.StudentAssignment;
import com.ympc.pojo.Teacher;
import com.ympc.pojo.Users;
import com.ympc.service.AssignmentService;
import com.ympc.service.ClassService;
import com.ympc.service.StudentAssignmentService;
import com.ympc.service.TeacherService;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpSession;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

/**
 * 作业管理控制器
 */
@Controller
@RequestMapping("/assignment")
public class AssignmentController {
    
    @Resource
    private AssignmentService assignmentService;
    
    @Resource
    private TeacherService teacherService;
    
    @Resource
    private ClassService classService;
    
    @Resource
    private StudentAssignmentService studentAssignmentService;
    
    /**
     * 发布作业页面
     */
    @RequestMapping(value = "/publish", method = RequestMethod.GET)
    public String publishPage(HttpSession session, Model model) {
        Users user = (Users) session.getAttribute("user");
        if (user == null) {
            return "redirect:/";
        }
        
        Teacher teacher = teacherService.getTeacherByUserId(user.getId());
        if (teacher == null || teacher.getId() == null) {
            model.addAttribute("error", "请先完善教师信息");
            return "redirect:/teacher/profile";
        }
        
        // 获取该教师管理的班级
        try {
            model.addAttribute("classes", classService.getClassesByTeacherId(teacher.getId()));
        } catch (Exception e) {
            e.printStackTrace();
            model.addAttribute("classes", new java.util.ArrayList<>());
            model.addAttribute("error", "获取班级列表时出错：" + e.getMessage());
        }
        return "assignment/publish";
    }
    
    /**
     * 发布作业
     */
    @RequestMapping(value = "/publish", method = RequestMethod.POST)
    public String publishAssignment(Assignment assignment,
                                    @RequestParam String deadlineStr,
                                    @RequestParam List<Integer> classIds,
                                    HttpSession session, Model model) {
        Users user = (Users) session.getAttribute("user");
        if (user == null) {
            return "redirect:/";
        }
        
        Teacher teacher = teacherService.getTeacherByUserId(user.getId());
        if (teacher == null || teacher.getId() == null) {
            model.addAttribute("error", "请先完善教师信息");
            return "redirect:/teacher/profile";
        }
        
        // 验证至少选择一个班级
        if (classIds == null || classIds.isEmpty()) {
            model.addAttribute("error", "请至少选择一个班级");
            model.addAttribute("classes", classService.getClassesByTeacherId(teacher.getId()));
            return "assignment/publish";
        }
        
        assignment.setTeacherId(teacher.getId());
        
        // 解析截止时间
        Date deadline;
        try {
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm");
            deadline = sdf.parse(deadlineStr);
            assignment.setDeadline(deadline);
        } catch (ParseException e) {
            model.addAttribute("error", "日期格式错误");
            model.addAttribute("classes", classService.getClassesByTeacherId(teacher.getId()));
            return "assignment/publish";
        }
        
        // 为每个选中的班级创建一条作业记录
        int successCount = 0;
        int failCount = 0;
        for (Integer classId : classIds) {
            Assignment assignmentCopy = new Assignment();
            assignmentCopy.setTeacherId(assignment.getTeacherId());
            assignmentCopy.setClassId(classId);
            assignmentCopy.setTitle(assignment.getTitle());
            assignmentCopy.setContent(assignment.getContent());
            assignmentCopy.setDeadline(deadline);
            
            if (assignmentService.publishAssignment(assignmentCopy)) {
                successCount++;
            } else {
                failCount++;
            }
        }
        
        if (successCount > 0) {
            if (failCount > 0) {
                model.addAttribute("message", "作业发布成功：" + successCount + "个班级，失败：" + failCount + "个班级");
            } else {
                model.addAttribute("message", "作业已成功发布到 " + successCount + " 个班级");
            }
            return "redirect:/assignment/list";
        } else {
            model.addAttribute("error", "作业发布失败，请重试");
            model.addAttribute("classes", classService.getClassesByTeacherId(teacher.getId()));
            return "assignment/publish";
        }
    }
    
    /**
     * 作业列表页面
     */
    @RequestMapping(value = "/list", method = RequestMethod.GET)
    public String assignmentList(@RequestParam(required = false) String status,
                                HttpSession session, Model model) {
        try {
            Users user = (Users) session.getAttribute("user");
            if (user == null) {
                return "redirect:/";
            }
            
            Teacher teacher = teacherService.getTeacherByUserId(user.getId());
            if (teacher == null) {
                model.addAttribute("error", "请先完善教师信息（需要先保存个人信息）");
                return "redirect:/teacher/profile";
            }
            
            if (teacher.getId() == null) {
                model.addAttribute("error", "教师信息未正确保存，请重新保存个人信息");
                return "redirect:/teacher/profile";
            }
            
            List<Assignment> assignments;
            try {
                if (status != null && !status.isEmpty()) {
                    assignments = assignmentService.getAssignmentsByTeacherIdAndStatus(teacher.getId(), status);
                } else {
                    assignments = assignmentService.getAssignmentsByTeacherId(teacher.getId());
                }
                // 确保返回的不是null
                if (assignments == null) {
                    assignments = new java.util.ArrayList<>();
                }
            } catch (Exception e) {
                e.printStackTrace();
                assignments = new java.util.ArrayList<>();
                model.addAttribute("error", "查询作业列表时出错：" + e.getMessage() + "。请检查数据库连接和表结构。");
            }
            
            // 获取所有班级信息，用于在页面中显示班级名称
            List<com.ympc.pojo.Class> allClasses = new java.util.ArrayList<>();
            try {
                allClasses = classService.getClassesByTeacherId(teacher.getId());
            } catch (Exception e) {
                e.printStackTrace();
            }
            
            model.addAttribute("assignments", assignments);
            model.addAttribute("allClasses", allClasses);
            model.addAttribute("status", status);
            return "assignment/list";
        } catch (Exception e) {
            e.printStackTrace();
            model.addAttribute("error", "访问作业管理时出错：" + e.getMessage());
            return "redirect:/teacher";
        }
    }
    
    /**
     * 批改作业页面
     */
    @RequestMapping(value = "/grading", method = RequestMethod.GET)
    public String gradingPage(HttpSession session, Model model) {
        Users user = (Users) session.getAttribute("user");
        if (user == null) {
            return "redirect:/";
        }
        
        Teacher teacher = teacherService.getTeacherByUserId(user.getId());
        if (teacher == null || teacher.getId() == null) {
            model.addAttribute("error", "请先完善教师信息");
            return "redirect:/teacher/profile";
        }
        
        try {
            List<Assignment> assignments = assignmentService.getAssignmentsByTeacherIdAndStatus(teacher.getId(), "published");
            model.addAttribute("assignments", assignments);
        } catch (Exception e) {
            e.printStackTrace();
            model.addAttribute("assignments", new java.util.ArrayList<>());
            model.addAttribute("error", "查询作业时出错：" + e.getMessage());
        }
        return "assignment/grading";
    }
    
    /**
     * 更新作业状态（批改完成）
     */
    @RequestMapping(value = "/finishGrading", method = RequestMethod.POST)
    public String finishGrading(@RequestParam Integer id, Model model) {
        boolean success = assignmentService.updateAssignmentStatus(id, "grading");
        if (success) {
            model.addAttribute("message", "作业状态已更新");
        } else {
            model.addAttribute("error", "更新失败");
        }
        return "redirect:/assignment/grading";
    }
    
    /**
     * 已结束作业列表
     */
    @RequestMapping(value = "/finished", method = RequestMethod.GET)
    public String finishedAssignments(HttpSession session, Model model) {
        Users user = (Users) session.getAttribute("user");
        if (user == null) {
            return "redirect:/";
        }
        
        Teacher teacher = teacherService.getTeacherByUserId(user.getId());
        if (teacher == null || teacher.getId() == null) {
            model.addAttribute("error", "请先完善教师信息");
            return "redirect:/teacher/profile";
        }
        
        try {
            List<Assignment> assignments = assignmentService.getAssignmentsByTeacherIdAndStatus(teacher.getId(), "finished");
            model.addAttribute("assignments", assignments);
        } catch (Exception e) {
            e.printStackTrace();
            model.addAttribute("assignments", new java.util.ArrayList<>());
            model.addAttribute("error", "查询作业时出错：" + e.getMessage());
        }
        return "assignment/finished";
    }
    
    /**
     * 结束作业
     */
    @RequestMapping(value = "/finish", method = RequestMethod.POST)
    public String finishAssignment(@RequestParam Integer id, Model model) {
        boolean success = assignmentService.updateAssignmentStatus(id, "finished");
        if (success) {
            model.addAttribute("message", "作业已结束");
        } else {
            model.addAttribute("error", "操作失败");
        }
        return "redirect:/assignment/list";
    }
    
    /**
     * 批改作业页面
     */
    @RequestMapping(value = "/grade", method = RequestMethod.GET)
    public String gradePage(@RequestParam Integer submissionId, HttpSession session, Model model) {
        Users user = (Users) session.getAttribute("user");
        if (user == null) {
            return "redirect:/";
        }
        
        Teacher teacher = teacherService.getTeacherByUserId(user.getId());
        if (teacher == null || teacher.getId() == null) {
            model.addAttribute("error", "请先完善教师信息");
            return "redirect:/teacher/profile";
        }
        
        try {
            StudentAssignment submission = studentAssignmentService.getSubmissionById(submissionId);
            if (submission == null) {
                model.addAttribute("error", "提交记录不存在");
                return "redirect:/assignment/list";
            }
            
            Assignment assignment = assignmentService.getAssignmentById(submission.getAssignmentId());
            model.addAttribute("submission", submission);
            model.addAttribute("assignment", assignment);
        } catch (Exception e) {
            e.printStackTrace();
            model.addAttribute("error", "获取批改信息时出错：" + e.getMessage());
            return "redirect:/assignment/list";
        }
        
        return "assignment/grade";
    }
    
    /**
     * 批改作业（提交评分和评语）
     */
    @RequestMapping(value = "/grade", method = RequestMethod.POST)
    public String gradeAssignment(@RequestParam Integer submissionId,
                                  @RequestParam Integer score,
                                  @RequestParam(required = false) String comment,
                                  HttpSession session, Model model) {
        Users user = (Users) session.getAttribute("user");
        if (user == null) {
            return "redirect:/";
        }
        
        Teacher teacher = teacherService.getTeacherByUserId(user.getId());
        if (teacher == null || teacher.getId() == null) {
            model.addAttribute("error", "请先完善教师信息");
            return "redirect:/teacher/profile";
        }
        
        // 验证分数范围
        if (score < 0 || score > 100) {
            model.addAttribute("error", "分数必须在0-100之间");
            StudentAssignment submission = studentAssignmentService.getSubmissionById(submissionId);
            Assignment assignment = assignmentService.getAssignmentById(submission.getAssignmentId());
            model.addAttribute("submission", submission);
            model.addAttribute("assignment", assignment);
            return "assignment/grade";
        }
        
        boolean success = studentAssignmentService.gradeAssignment(submissionId, score, comment);
        if (success) {
            model.addAttribute("message", "批改成功");
            // 获取提交记录以获取assignmentId
            StudentAssignment submission = studentAssignmentService.getSubmissionById(submissionId);
            if (submission != null) {
                Assignment assignment = assignmentService.getAssignmentById(submission.getAssignmentId());
                if (assignment != null) {
                    // 获取班级ID，返回学生完成情况页面
                    return "redirect:/class/studentStatus?classId=" + assignment.getClassId() + "&assignmentId=" + assignment.getId();
                }
            }
            return "redirect:/assignment/list";
        } else {
            model.addAttribute("error", "批改失败，请重试");
            StudentAssignment submission = studentAssignmentService.getSubmissionById(submissionId);
            Assignment assignment = assignmentService.getAssignmentById(submission.getAssignmentId());
            model.addAttribute("submission", submission);
            model.addAttribute("assignment", assignment);
            return "assignment/grade";
        }
    }
    
    /**
     * 查看作业的学生完成情况（选择班级）
     */
    @RequestMapping(value = "/viewStudents", method = RequestMethod.GET)
    public String viewStudentsPage(@RequestParam Integer assignmentId, HttpSession session, Model model) {
        Users user = (Users) session.getAttribute("user");
        if (user == null) {
            return "redirect:/";
        }
        
        Teacher teacher = teacherService.getTeacherByUserId(user.getId());
        if (teacher == null || teacher.getId() == null) {
            model.addAttribute("error", "请先完善教师信息");
            return "redirect:/teacher/profile";
        }
        
        Assignment assignment = assignmentService.getAssignmentById(assignmentId);
        if (assignment == null) {
            model.addAttribute("error", "作业不存在");
            return "redirect:/assignment/list";
        }
        
        // 获取该作业的班级信息
        com.ympc.pojo.Class clazz = null;
        if (assignment.getClassId() != null) {
            try {
                clazz = classService.getClassById(assignment.getClassId());
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        
        if (clazz == null) {
            model.addAttribute("error", "班级不存在");
            return "redirect:/assignment/list";
        }
        
        // 直接跳转到学生完成情况页面
        return "redirect:/class/studentStatus?classId=" + assignment.getClassId() + "&assignmentId=" + assignmentId;
    }
}

